<?php

/**
 * @
 * @Description:
 * @Copyright (C) 2011 helloweba.com,All Rights Reserved.
 * -----------------------------------------------------------------------------
 * @author: Liurenfei (lrfbeyond@163.com)
 * @Create: 2012-5-1
 * @Modify:
*/
include_once ("connect.php");

$action = $_GET['action'];
if ($action == 'import') { //导入CSV
    $filename = $_FILES['file']['tmp_name'];
    if (empty ($filename)) {
        echo '请选择要导入的CSV文件！';
        exit;
    }

    // echo $filename;
    // echo '<br/>';
    $handle = fopen($filename, 'r');
    // $handle = fopen('aaaa.csv', 'r');
    $result = input_csv($handle); //解析csv


    $len_result = count($result);
    if($len_result==0){
        echo '没有任何数据！';
        exit;
    }
    // var_dump($result);
    // var_dump($len_result);
    // exit;
    



    $namet = $_FILES['file']['name'];
    $laoshi_id=$link->query("select max(name_id) as a from name where name='".$_COOKIE['name']."'");

    $laoshi_id=mysqli_fetch_assoc($laoshi_id)['a'];

    $link->query("insert into tikuzhuce (name,laoshi_id) values ('$namet',$laoshi_id)");
    $resul = $link->query("select max(id) as a from tikuzhuce");
    $id=mysqli_fetch_assoc($resul)['a'];



    for ($i = 0; $i < $len_result; $i++) { //循环获取各字段值

        $timu =  $result[$i][0]; //中文转码
        $a = $result[$i][1];
        $b = $result[$i][2];
        $c = $result[$i][3];
        $d = $result[$i][4];
        $daan = iconv('GB13000', 'utf-8', $result[$i][5]);
        // $age = $result[$i][2];
        // $data_values .= "('$name','$sex','$age'),";
        $data_values .= "($id,'$timu','$a','$b','$c','$d','$daan'),";
    }
    $data_values = substr($data_values,0,-1); //去掉最后一个逗号
    fclose($handle); //关闭指针
   // var_dump($data_values);
    $query = $link->query("insert into ceshi (juanzi_id,timu,a,b,c,d,daan) values $data_values");//批量插入数据表中
    if($query){
        echo '导入成功！';
    }else{
        echo '导入失败！';
    }


}/* elseif ($action=='export') { //导出CSV
    $result = $link->query("select * from aa");
    $str = "id,uniprot,url\n";
    $str = iconv('utf-8','gb2312',$str);
    while($row=mysql_fetch_array($result)){
        $name = iconv('utf-8','gb2312',$row['id']);
        $sex = iconv('utf-8','gb2312',$row['uniprot']);  
        $str .= $name.",".$sex.",".$row['url']."\n";
    }
    $filename = date('Ymd').'.csv';
    export_csv($filename,$str);
}*/
function input_csv($handle) {
    $out = array ();
    $n = 0;
    while ($data = fgetcsv($handle, 10000)) {
        $num = count($data);
        for ($i = 0; $i < $num; $i++) {
            $out[$n][$i] = $data[$i];
        }
        $n++;
    }
    return $out;
}

function export_csv($filename,$data) {
    header("Content-type:text/csv");
    header("Content-Disposition:attachment;filename=".$filename);
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    echo $data;
}
?>